package com.sinochem.yunlian.ship.common.filter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.google.common.base.Strings;
import com.sinochem.yunlian.ship.common.annotation.IgnoreToken;
import com.sinochem.yunlian.ship.common.enums.ResponseCode;
import com.sinochem.yunlian.ship.common.exception.BaseException;

public class AuthRestInterceptor extends HandlerInterceptorAdapter {
    
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
 
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        // 配置该注解，说明不进行用户拦截
        IgnoreToken annotation = handlerMethod.getBeanType().getAnnotation(IgnoreToken.class);
        if (annotation == null) {
            annotation = handlerMethod.getMethodAnnotation(IgnoreToken.class);
        }
        if(annotation!=null) {
            return super.preHandle(request, response, handler);
        }

        String userId = request.getHeader("currentUserId");

		// 未获取到从paramter中获取
		if(Strings.isNullOrEmpty(userId)){
			throw new BaseException(ResponseCode.UN_AUTH.getName(),
					new Integer(ResponseCode.UN_AUTH.getCode()));
		}
        
        return super.preHandle(request, response, handler);
    }
    
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }
    
}
